package com.robusta.cityuate.activities;

import java.util.Calendar;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.robusta.cityuate.R;
import com.robusta.cityuate.base.CityuateFragmentActivity;
import com.robusta.cityuate.dialogs.CountryPickerFragment;
import com.robusta.cityuate.dialogs.CountryPickerFragment.CountryPickerCallback;
import com.robusta.cityuate.dialogs.DatePickerFragment;
import com.robusta.cityuate.dialogs.PasswordConfirmationDialog;
import com.robusta.cityuate.dialogs.PasswordConfirmationDialog.PasswordEnteredCallBack;
import com.robusta.cityuate.objects.Country;
import com.robusta.cityuate.objects.User;
import com.robusta.cityuate.services.CityuateBroadCastReceiver;
import com.robusta.cityuate.services.EditUserProfileService;
import com.robusta.cityuate.services.HTTPService;
import com.robusta.cityuate.utils.ConnectionUtils;
import com.robusta.cityuate.utils.TimeUtils;

public class EditUserProfileActivity extends CityuateFragmentActivity implements
		TextWatcher, PasswordEnteredCallBack, CountryPickerCallback{

	public static final int EDIT_ACTIVITY_CODE = 10;
	protected static final int DATE_OF_BIRTH_DIALOG = 20;
	private static final String DATE_PICKER_TAG = "DateTime";
	private EditText firstNameField;
	private EditText lastNameField;
	private EditText userNameField;
	private EditText emailField;
	private EditText dateOfBirthField;
	private EditText mobileField;
	private EditText zipCodeField;
	private EditText countryField;
	private EditText cityField;
	private EditText districtField;
	private EditText buildNumField;
	private EditText streetField;
	private Button updateButton;
	private Button cancelButton;
	private EditText new_pwd;
	private EditText new_pwd_confirm;
	// private int country_id;
	private String currentPassword;
	private Country mCountry;
	PasswordConfirmationDialog confirmPassDialog;

	private String TAG = EditUserProfileActivity.class.getName();
	private final Context mContext = this;
	// private final int CONFIMEPASSWORD = 0;
	private CityuateBroadCastReceiver receiver = new CityuateBroadCastReceiver() {

		@Override
		public void onSuccess() {
			updateSuccess();
		}

		@Override
		public void onFailure() {
			updateFail();
		}

		@Override
		public void onCancel() {
			enableView();
			setSupportProgressBarIndeterminateVisibility(false);
			ConnectionUtils.clearConnection(mContext, TAG);

		}

	};
	private User user;

	// private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_profile_view);

		firstNameField = (EditText) findViewById(R.id.firstname);
		lastNameField = (EditText) findViewById(R.id.lastname);
		userNameField = (EditText) findViewById(R.id.usrname);
		emailField = (EditText) findViewById(R.id.email);
		dateOfBirthField = (EditText) findViewById(R.id.dateofbirth);
		mobileField = (EditText) findViewById(R.id.mobilnum);
		zipCodeField = (EditText) findViewById(R.id.zipcode);
		countryField = (EditText) findViewById(R.id.country);
		// making country field noneditable
		countryField.setFocusable(false);
		countryField.setFocusableInTouchMode(false);
		countryField.setKeyListener(null);

		// Edit conntry through activity
		countryField.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// initialize intent to get
				CountryPickerFragment countrypick = CountryPickerFragment
						.getInstance(v.getId(), mCountry);
				countrypick.show(getSupportFragmentManager(), "Pick_Country");
			}
		});
		cityField = (EditText) findViewById(R.id.city);
		districtField = (EditText) findViewById(R.id.district);
		buildNumField = (EditText) findViewById(R.id.buildnum);
		streetField = (EditText) findViewById(R.id.street);

		new_pwd = (EditText) findViewById(R.id.pwd_f);
		new_pwd_confirm = (EditText) findViewById(R.id.pwd_s);

		updateButton = (Button) findViewById(R.id.btn_update);
		updateButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (new_pwd.getText().toString()
						.equals(new_pwd_confirm.getText().toString()))
					showPasswordConfirmDialog();
				else
					Toast.makeText(mContext,
							getString(R.string.reg_pwd_match_err),
							Toast.LENGTH_SHORT).show();
			}

		});

		cancelButton = (Button) findViewById(R.id.btn_cancel);
		cancelButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if (ConnectionUtils.isConnecting(mContext, TAG)) {
					enableView();
					setSupportProgressBarIndeterminateVisibility(false);
					Intent loginCancel = new Intent(TAG + HTTPService.CANCEL);
					sendBroadcast(loginCancel);
					ConnectionUtils.clearConnection(mContext, TAG);
				} else {
					setResult(RESULT_CANCELED);
					finish();
				}
			}
		});

		// fill data
		user = (User) getIntent().getExtras().getSerializable(
				UserProfileActivity.TAG + "." + User.USER);
		Log.e(UserProfileActivity.TAG + "." + User.USER, "" + (user == null));
		firstNameField.setText(user.getFirst_name());
		lastNameField.setText(user.getLast_name());
		userNameField.setText(user.getUsername());
		emailField.setText(user.getEmail());
		dateOfBirthField.setText(TimeUtils.changeDateFormat(user.getDob(),
				"yyyy-MM-dd", "MMM dd, yyyy"));
		mobileField.setText(user.getMobile_number());
		zipCodeField.setText(user.getZip_code());
		countryField.setText(user.getCountry_name());
		cityField.setText(user.getCity());
		districtField.setText(user.getDistrict());
		buildNumField.setText(user.getBuilding_number());
		streetField.setText(user.getStreet());
		mCountry = new Country(user.getCountry_id(), user.getCountry_code(),
				user.getCountry_name());
		// country_id = user.getCountry_id();

		// add change listener
		dateOfBirthField.addTextChangedListener(this);
		firstNameField.addTextChangedListener(this);
		lastNameField.addTextChangedListener(this);
		userNameField.addTextChangedListener(this);
		emailField.addTextChangedListener(this);
		new_pwd.addTextChangedListener(this);
		new_pwd_confirm.addTextChangedListener(this);
		countryField.addTextChangedListener(this);
		mobileField.addTextChangedListener(this);
		cityField.addTextChangedListener(this);
		districtField.addTextChangedListener(this);
		streetField.addTextChangedListener(this);
		buildNumField.addTextChangedListener(this);
		zipCodeField.addTextChangedListener(this);

		getSupportActionBar().setTitle(
				user.getFirst_name() + " " + user.getLast_name());
		getSupportActionBar().setSubtitle(R.string.edit_profile);

	}

	@Override
	protected void onPause() {
		unregisterReceiver(receiver);
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (!ConnectionUtils.isConnecting(mContext, TAG))
			ConnectionUtils.clearConnection(mContext, TAG);

	}

	@Override
	protected void onResume() {
		IntentFilter filter = new IntentFilter(TAG);
		registerReceiver(receiver, filter);

		if (ConnectionUtils.isConnecting(mContext, TAG)) {// showLoadingDialog();
			setSupportProgressBarIndeterminateVisibility(true);
		} else if (ConnectionUtils.wasConnected(mContext, TAG))
			if (ConnectionUtils.isResultSuccessful(mContext, TAG))
				updateSuccess();
			else
				updateFail();

		super.onResume();
	}

	private void updateSuccess() {
		enableView();
		setSupportProgressBarIndeterminateVisibility(false);
		Toast.makeText(mContext, getString(R.string.profile_edit_success),
				Toast.LENGTH_LONG).show();
		setResult(RESULT_OK);

		finish();

	}

	private void updateFail() {
		enableView();
		setSupportProgressBarIndeterminateVisibility(false);
		Log.d(TAG, "Edit Fail method");
		// show failure message
		Toast.makeText(mContext, ConnectionUtils.getExtra(mContext, TAG),
				Toast.LENGTH_LONG).show();
		ConnectionUtils.clearConnection(mContext, TAG);
	}

	@Override
	public void afterTextChanged(Editable arg0) {
		if (new_pwd.getText().length() == 0)

			if (dateOfBirthField.getText().length() != 0
					&& firstNameField.getText().length() != 0
					&& lastNameField.getText().length() != 0
					&& userNameField.getText().length() != 0
					&& emailField.getText().length() != 0
					&& countryField.getText().length() != 0
					&& mobileField.getText().length() != 0
					&& cityField.getText().length() != 0
					&& districtField.getText().length() != 0
					&& streetField.getText().length() != 0
					&& buildNumField.getText().length() != 0
					&& zipCodeField.getText().length() != 0)

				updateButton.setEnabled(true);
			else
				updateButton.setEnabled(false);
		else if (new_pwd_confirm.getText().length() != 0)
			updateButton.setEnabled(true);
		else
			updateButton.setEnabled(false);

	}

	private void updateUserData() {
		// Check if no connection pop up a dialog
		if (!ConnectionUtils.isNetworkAvailable(mContext)) {
			// No connection
			ConnectionUtils.showNoConnectionDialog(mContext);
			return;
		} else { // Connection is available
			disableView();
			
			setSupportProgressBarIndeterminateVisibility(true);
			// start back-ground service to handle registration process
			Intent backgroud_regService = new Intent(this,
					EditUserProfileService.class);
			backgroud_regService.setAction(TAG);

			backgroud_regService.putExtra(HTTPService.LOGIN_RQUIRED, true);
			backgroud_regService.putExtra(User.USER_CURRENT_PWD,
					currentPassword);

			backgroud_regService.putExtra(User.USER_EMAIL, emailField.getText()
					.toString());
			if (new_pwd.getText().length() != 0)
				backgroud_regService.putExtra(User.USER_PWD, new_pwd.getText()
						.toString());
			backgroud_regService.putExtra(User.USER_BUILDING_NUMBER,
					buildNumField.getText().toString());
			backgroud_regService.putExtra(User.USER_CITY, cityField.getText()
					.toString());
			backgroud_regService.putExtra(User.USER_DISTRICT, districtField
					.getText().toString());
			backgroud_regService.putExtra(User.USER_FIRST_NAME, firstNameField
					.getText().toString());
			backgroud_regService.putExtra(User.USER_LAST_NAME, lastNameField
					.getText().toString());
			backgroud_regService.putExtra(User.USER_USERNAME, userNameField
					.getText().toString());
			backgroud_regService.putExtra(User.USER_DISTRICT, districtField
					.getText().toString());
			backgroud_regService.putExtra(User.USER_MOBILE_NUMBER, mobileField
					.getText().toString());
			backgroud_regService.putExtra(User.USER_STREET, streetField
					.getText().toString());
			backgroud_regService.putExtra(User.USER_ZIP_CODE, zipCodeField
					.getText().toString());

			Calendar c = TimeUtils.getCalendarFromFormat(dateOfBirthField
					.getText().toString(), "MMM dd, yyyy");

			backgroud_regService.putExtra(User.USER_DOB_1I,
					c.get(Calendar.YEAR));
			backgroud_regService.putExtra(User.USER_DOB_2I,
					c.get(Calendar.MONTH)+1);
			backgroud_regService.putExtra(User.USER_DOB_3I,
					c.get(Calendar.DAY_OF_MONTH));

			backgroud_regService.putExtra(User.USER_COUNTRY_ID,
					mCountry.getId());

			startService(backgroud_regService);
			Log.e(TAG, "Fired EditUserProfile service");

		}

	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
	}

	public void showDatePicker(View v) {
		DialogFragment newFragment = DatePickerFragment.getInstance(
				v.getId(), null, Calendar.getInstance());
		newFragment.show(getSupportFragmentManager(), DATE_PICKER_TAG);
	}

	@Override
	public void onPasswordConfirmed(String password) {
		currentPassword = password;
		updateUserData();
	}

	private void showPasswordConfirmDialog() {
		FragmentManager fm = getSupportFragmentManager();
		confirmPassDialog = PasswordConfirmationDialog.getInstant();
		confirmPassDialog.show(fm, "ConfirmPassword");

	}

	private void disableView() {
		dateOfBirthField.setEnabled(false);
		firstNameField.setEnabled(false);
		lastNameField.setEnabled(false);
		userNameField.setEnabled(false);
		emailField.setEnabled(false);
		new_pwd.setEnabled(false);
		new_pwd_confirm.setEnabled(false);
		countryField.setEnabled(false);
		mobileField.setEnabled(false);
		cityField.setEnabled(false);
		districtField.setEnabled(false);
		streetField.setEnabled(false);
		buildNumField.setEnabled(false);
		zipCodeField.setEnabled(false);

		updateButton.setEnabled(false);

	}

	private void enableView() {
		dateOfBirthField.setEnabled(true);
		firstNameField.setEnabled(true);
		lastNameField.setEnabled(true);
		userNameField.setEnabled(true);
		emailField.setEnabled(true);
		new_pwd.setEnabled(true);
		new_pwd_confirm.setEnabled(true);
		countryField.setEnabled(true);
		mobileField.setEnabled(true);
		cityField.setEnabled(true);
		districtField.setEnabled(true);
		streetField.setEnabled(true);
		buildNumField.setEnabled(true);
		zipCodeField.setEnabled(true);

		updateButton.setEnabled(true);

	}

	@Override
	public void onBackPressed() {
		if (ConnectionUtils.isConnecting(mContext, TAG)) {
			enableView();
			setSupportProgressBarIndeterminateVisibility(false);
			Intent loginCancel = new Intent(TAG + HTTPService.CANCEL);
			sendBroadcast(loginCancel);
			ConnectionUtils.clearConnection(mContext, TAG);
		} else
			super.onBackPressed();
	}

	@Override
	public void setCountry(Country country) {
		mCountry=country;
		
	}

}
